//! 数据库填充模块

#[cfg(feature = "database")]
use sqlx::{Database, Pool};
use serde_json::Value;
use crate::error::{DataForgeError, Result};

#[cfg(feature = "database")]
/// 数据库填充器
pub struct DatabaseForge<DB: Database> {
    pool: Pool<DB>,
    tables: Vec<TableConfig>,
}

/// 表配置
pub struct TableConfig {
    pub name: String,
    pub count: usize,
    pub fields: Vec<FieldConfig>,
}

/// 字段配置
pub struct FieldConfig {
    pub name: String,
    pub generator: Box<dyn Fn() -> Value + Send + Sync>,
}

#[cfg(feature = "database")]
impl<DB: Database> DatabaseForge<DB> {
    /// 创建新的数据库填充器
    pub fn new(pool: Pool<DB>) -> Self {
        Self {
            pool,
            tables: Vec::new(),
        }
    }

    /// 添加表配置
    pub fn table<F>(mut self, name: &str, count: usize, config: F) -> Self
    where
        F: FnOnce(&mut TableBuilder) -> &mut TableBuilder,
    {
        let mut builder = TableBuilder::new(name.to_string());
        config(&mut builder);
        self.tables.push(builder.build(count));
        self
    }

    /// 执行数据填充
    pub async fn fill(&self) -> Result<()> {
        for table in &self.tables {
            self.fill_table(table).await?;
        }
        Ok(())
    }

    /// 填充单个表
    async fn fill_table(&self, table: &TableConfig) -> Result<()> {
        // 这里需要根据具体的数据库类型实现
        // 由于这是一个通用实现，我们只提供接口
        todo!("Database-specific implementation needed")
    }
}

/// 表构建器
pub struct TableBuilder {
    name: String,
    fields: Vec<FieldConfig>,
}

impl TableBuilder {
    fn new(name: String) -> Self {
        Self {
            name,
            fields: Vec::new(),
        }
    }

    /// 添加字段
    pub fn field<F>(&mut self, name: &str, generator: F) -> &mut Self
    where
        F: Fn() -> Value + Send + Sync + 'static,
    {
        self.fields.push(FieldConfig {
            name: name.to_string(),
            generator: Box::new(generator),
        });
        self
    }

    fn build(self, count: usize) -> TableConfig {
        TableConfig {
            name: self.name,
            count,
            fields: self.fields,
        }
    }
}

/// MySQL 数据库填充器
#[cfg(feature = "database")]
pub type MySqlForge = DatabaseForge<sqlx::MySql>;

/// PostgreSQL 数据库填充器
#[cfg(feature = "database")]
pub type PostgresForge = DatabaseForge<sqlx::Postgres>;

/// SQLite 数据库填充器
#[cfg(feature = "database")]
pub type SqliteForge = DatabaseForge<sqlx::Sqlite>;

#[cfg(all(test, feature = "database"))]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_table_builder() {
        let mut builder = TableBuilder::new("users".to_string());
        builder
            .field("id", || Value::String("test".to_string()))
            .field("name", || Value::String("test_name".to_string()));

        let table = builder.build(100);
        assert_eq!(table.name, "users");
        assert_eq!(table.count, 100);
        assert_eq!(table.fields.len(), 2);
    }
}